<script setup>
import {ref, onMounted} from 'vue'
import {useRouter} from 'vue-router'
import axios from 'axios'

const token = localStorage.getItem('token')
const topstorylist = ref ([])
const currentPage = ref(1);  // 当前页码
const pageSize = ref(10);    // 每页条数
const total = ref(0);        // 数据总数
// 处理分页变化的函数
const router = useRouter()
const handleCurrentChange = async (page) => {
  currentPage.value = page;
  // 发送请求获取对应页的数据
  await fetchData();
};
const fetchData = async () => {
  try {
    const response = await axios.post('http://127.0.0.1:8000/user/api/topic/', {
      page: currentPage.value,  // 发送当前页码给后端
      page_size: pageSize.value  // 发送每页条数给后端
    }, {
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    });
   
    topstorylist.value = response.data.data;
    total.value = response.data.total;  // 设置数据总数
  } catch (error) {
    console.error('Error fetching data', error);
  }
};
onMounted(async () => {
  await fetchData();  // 页面加载时立即获取第一页的数据
});
//跳转到详情页
function goDetails(v) {
  router.push({ 
    name: 'topicdetails',
    params: { 
      id: v.id
    } 
  });
}

// 定义赞成按钮的点击事件处理函数
async function voteUp(v) {
  if (!token) {
    alert('请先登录');
    return;
  }
  try {
    // 向后端发送请求，表示对指定话题进行点赞
    const response = await axios.post(`http://127.0.0.1:8000/user/api/vote_up/${v.id}/`);
    // 根据后端返回的数据更新前端页面
    const updatedTopic = response.data; // 假设后端返回更新后的话题对象
    const index = topstorylist.value.findIndex(topic => topic.id === v.id);
    if (index !== -1) {
      topstorylist.value[index] = updatedTopic; // 更新话题列表中的对应项
    }
    window.location.reload(); // 重新加载页面
  } catch (error) {
    console.error('赞成失败', error);
    // 处理请求失败的情况
  }
}
// 不赞成按钮的点击事件处理函数
async function voteDown(v) {
  if (!token) {
    alert('请先登录');
    return;}
  try {
    // 向后端发送请求，表示对指定话题进行点赞
    const response = await axios.post(`http://127.0.0.1:8000/user/api/vote_down/${v.id}/`);
    // 根据后端返回的数据更新前端页面
    const updatedTopic = response.data; // 假设后端返回更新后的话题对象
    const index = topstorylist.value.findIndex(topic => topic.id === v.id);
    if (index !== -1) {
      topstorylist.value[index] = updatedTopic; // 更新话题列表中的对应项
    }
    window.location.reload(); // 重新加载页面
  } catch (error) {
    console.error('赞成失败', error);
    // 处理请求失败的情况
  }
}

//收藏按钮的点击事件处理函数
async function collectTopic(v) {
  if (!token) {
    alert('请先登录');
    return;}
  try {
    const response = await axios.post('http://127.0.0.1:8000/user/api/collect_topic/', {
      topic_id: v.id,
      token: token
    }, {
      headers: {
        'Content-Type': 'application/json'
      },
    });
   alert(response.data.message)
   
  } catch (error) {
    console.error('收藏失败', error);
    // 处理请求失败的情况
  }
}
function gousermsg(id) {
    router.push({ 
    name: 'usermsg',
    params: { 
      id: id
    } 
  });
}
</script>

<template>
    <div class="Topstory-content">
        <ul>
            <li v-for="v in topstorylist" :key="v.id">
              <div>
                <h2 class="topic-title" @click="goDetails(v)">{{ v.title }}</h2>
                <div class="topstory-hd" @click="gousermsg(v.id)">
                  <span>{{ v.publisher_name }}</span>
              </div>
                <div class="topic-content" @click="goDetails(v)">{{ v.content }}</div>
                <div>
                    <p class="publish-time">发布时间:{{ v.publish_time }}</p>
                </div>
            </div>
            <el-row :gutter="20" class="action-area">
                <el-col :span="4">
                    <el-button type="text" @click="voteUp(v)">
                        <i class="iconfont icon-xiangshang1"></i> 赞成 {{ v.likes_number }}
                    </el-button>
                </el-col>
                <el-col :span="4">
                    <el-button type="text" @click="voteDown(v)">
                        <i class="iconfont icon-xiangxia2"></i>反对{{ v.dislikes_number }}
                    </el-button>
                </el-col>
                <el-col :span="4">
                    <el-button type="text"  @click="goDetails(v)">
                        <i class="iconfont icon-xiaoxi"></i> {{ v.comment_count }}
                    </el-button>
                </el-col>
                <el-col :span="4">
                    <el-button type="text" @click="collectTopic(v)">
                        <i class="iconfont icon-shoucang"></i> 收藏
                    </el-button>
                </el-col>
              
            </el-row>

            </li>
        </ul>
    
    </div>
    <div class="Topstory-content">
        <el-pagination
    :page-size="10"
    :pager-count="10"
    @current-change="handleCurrentChange"
    layout="prev, pager,next"
    :total="total"
  />
      </div>

</template>

<style scoped>
/* 话题列表项 */
.topic-item {
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 10px;
  margin-bottom: 10px;
}

/* 话题标题 */
.topic-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 5px;
}

/* 话题内容 */
.topic-content {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

/* 发布时间 */
.publish-time {
  font-size: 12px;
  color: #999;
}

/* 动作区 */
.action-area {
  align-items: center;
}
</style>
